<?php 
// +----------------------------------------------------------------------
// | 狂团[kt8.cn]旗下KtAdmin是为独立版SAAS系统而生的快速开发框架.
// +----------------------------------------------------------------------
// | [KtAdmin] Copyright (c) 2022 http://ktadmin.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------

namespace app\base\controller\admin;

use think\facade\Db;
use think\facade\Session;
use app\BaseController;
use app\base\model\admin\system\KtModel;

/**
* 插件安装更新
*/
class AppInstall extends BaseController
{
	public function index()
	{
		$orderbh = request()->get('orderbh');
		$operation = request()->get('operation');
		$uid = KtModel::getAdminId();
		$config = Db::table('kt_base_ktconfig')->where('uid',$uid)->find();
		if(!$config) exi('error'); 
		$params = [
			'key' => $config['key'],
			'secret' => $config['secret'],
			'orderbh' => $orderbh,
		];
		$detail = KtModel::getModuleDetailApi($params);
		if(!isset($detail['status']) || $detail['status'] != 'success'){
			echo 'error';
			exit;
		}
		$pulgin = $detail['data'];
		$module = Db::table('kt_base_kt_plugin')->where('code',$pulgin['name'])->find();
		$data = [
			'uid' => $uid,
			'name' => $pulgin['title'],
			'code' => $pulgin['name'],
			'orderbh' => $pulgin['orderbh'],
			'logo' => $pulgin['logo'] ?? '',
			'update_time' => date("Y-m-d H:i:s"),
			'install_type' => 2,
		];
		$data = [];
		if(!$module){
			$data['create_time'] = date("Y-m-d H:i:s");
			$operation = 'install';	
		}else{
			$data['id'] = $module['id'];
			if($operation == 'upgrade' && $module['version'] == $pulgin['version']){
				echo 'error';
				exit;
			}
		}
		
		$data['version'] = $pulgin['version'];
		$data['expire_date'] = $pulgin['expire_date'];
		
		$params = [
			'key' => $config['key'],
			'secret' => $config['secret'],
			'orderbh' => $orderbh,
		];
		$downPlugin = KtModel::downModuleApi($params);

		if($downPlugin['status'] != 'success'){
			echo 'error';
			exit;
		}
		//资源文件名
		$file_name = $downPlugin['data']['filename'];
		$resource = $downPlugin['data']['resource'];
		$path = root_path().'static/temp/module/';
		is_dir($path) or mkdir($path, 0777, true);
		$file_path = $path.'/'.$file_name;
		$res = file_put_contents($file_path, base64_decode($resource));

		$zipName = $file_name;
		if(!file_exists($file_path)) exit;
		$zipArc = new \ZipArchive();
		if (!$zipArc->open($file_path)) exit('安装失败');
		if (!$zipArc->extractTo(root_path().'app')) {
			$zipArc->close();
			exit('安装失败');
		}

		//插件目录
		$nameIndex = $zipArc->getNameIndex(0);
		$zipArc->close();
		$nameIndexArr = explode('/', $nameIndex);
		$name = $nameIndexArr[0];
		//前后端分离 需将编译后代码解压到public/app下
		$htmlZipPath = root_path().'app'.'/'.$name.'/dist.zip';
		if(file_exists($htmlZipPath)){
			$zipArc = new \ZipArchive();
			$zipArc->open($htmlZipPath);
			is_dir(root_path().'public/app/'.$name) or mkdir(root_path().'public/app/'.$name, 0777, true);
			$zipArc->extractTo(root_path().'public/app/'.$name);
			$zipArc->close();
		}

		$xml = simplexml_load_file(root_path().'app/'.$name.'/manifest.xml','SimpleXMLElement', LIBXML_NOCDATA);
		$xml_arr = json_decode(json_encode($xml), 1);
		$data['user_link'] = $xml_arr['application']['userindex'] ?? '';
		$data['admin_link'] = $xml_arr['application']['adminindex'] ?? '';
		$data['target'] = $xml_arr['application']['target'] ?? 2;
		$data['describe'] = $xml_arr['application']['describe'] ?? '';
		$data['app_type'] = $xml_arr['application']['type'] ?? 1;
		$data['author'] = $xml_arr['application']['author'] ?? '';

		if($data['app_type'] == 2){
			$nameArr = explode('_', $xmlArr['application']['code']);
			if($data['app_type']=2  && in_array('plugin', $nameArr)){
				$key = array_keys($nameArr,'plugin');
    			$panmeArr = array_slice($nameArr, 0,$key);
    			$pname = implode('_', $panmeArr);
    			$data['pid'] = Db::table("kt_base_market_app")->where(["code"=>$pname])->value('id') ?: 0;
			}
		}
		$sqla = '';
		$upgradePath = root_path().'/app/'.$name.'/upgrade';
		if($operation == 'install'){
			$data['code'] = $xml_arr['application']['code'];
			$data['name'] = $xml_arr['application']['name'];
			if(is_dir($upgradePath)){
				$versionDirs = scandir($upgradePath);
				sort($versionDirs);
				if($versionDirs){
					foreach ($versionDirs as $versionDir) {
						if($versionDir == "." || $versionDir == ".." ) continue;
						$sqla = '';
						if(file_exists($upgradePath.'/'.$versionDir.'/Up.php')){
							$sqlArr = include($upgradePath.'/'.$versionDir.'/Up.php');
							foreach ((array)$sqlArr as $val) {
								$sqla .= $val;
							}
						}
						if($sqla){
							$resRunSql = Db::execute($sqla);
							if($resRunSql['status'] !== 'success'){
								 \Log::error('sql执行错误:' . $resRunSql['msg']);
							}
						}
						$data['version'] = $versionDir;
					}
				}
			}
		}else if($operation == 'upgrade'){
			if(is_dir($upgradePath)){
				$versionDirs = scandir($upgradePath);
				foreach ($versionDirs as $key => $value) {
					if($value == "." || $value == ".." ) unset($versionDirs[$key]);
				}
				sort($versionDirs);
				if($versionDirs){
					// arsort($versionDirs);
					$versionDirKey = array_keys($versionDirs,$module['version'])[0];
					for ($i=$versionDirKey + 1; $i < count($versionDirs); $i++) { 
						$sqla = '';
						if(file_exists($upgradePath.'/'.$versionDirs[$i].'/Up.php')){
							$sqlArr = include($upgradePath.'/'.$versionDirs[$i].'/Up.php');
							foreach ((array)$sqlArr as $k => $val) {
								$sqla .= $val;
							}
						}
						if($sqla){
							$resRunSql = Db::execute($sqla);
							if($resRunSql['status'] !== 'success'){
								 \Log::error('sql执行错误:' . $resRunSql['msg']);
							}
						}
						$data['version'] = $versionDirs[$i];
					}
				}
			}
		}

		// $data['status'] =  1;
		// $data['can_update'] = 0;
		Db::table('kt_base_market_app')->save($data);
		unlink($file_path);
		echo 'success';
		exit;
	}
}